package com.user_service.controller;

import com.user_service.bean.User;
import com.user_service.bean.LoginRequest;
import com.user_service.bean.LoginResponse;
import com.user_service.bean.ApiResponse;
import com.user_service.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

// 创建用于接收注册请求的DTO类
class RegisterRequest {
    private String username;
    private String password;
    private String email;

    // Getters and setters
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

@RestController
@RequestMapping("/auth")  // 恢复为/auth路径，以匹配API网关路由规则
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;

    // 为了保持向后兼容，保留原有的注册接口
    @PostMapping("/register/legacy")
    public ResponseEntity<ApiResponse<?>> registerUser(@RequestParam String username,
                                               @RequestParam String password,
                                               @RequestParam String email){
        if(userService.existsByUsername(username)){
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "用户名已存在"));
        }

        try{
            User user = userService.registerUser(username, password, email);
            // 创建返回数据对象
            UserData userData = new UserData();
            userData.setUserId(user.getId());
            userData.setUsername(user.getUsername());
            
            return ResponseEntity.ok(ApiResponse.success("注册成功", userData));
        }catch (Exception  e){
            return ResponseEntity.status(500).body(ApiResponse.error(500, "用户注册失败"+e.getMessage()));
        }
    }
    
    // 添加符合新路径规范的注册接口
    @PostMapping("/register")
    public ResponseEntity<ApiResponse<UserData>> registerUserNew(@RequestBody RegisterRequest registerRequest){
        if(userService.existsByUsername(registerRequest.getUsername())){
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "用户名已存在"));
        }

        try{
            User user = userService.registerUser(registerRequest.getUsername(), registerRequest.getPassword(), registerRequest.getEmail());
            // 创建返回数据对象
            UserData userData = new UserData();
            userData.setUserId(user.getId());
            userData.setUsername(user.getUsername());
            
            return ResponseEntity.ok(ApiResponse.success("注册成功", userData));
        }catch (Exception  e){
            return ResponseEntity.status(500).body(ApiResponse.error(500, "用户注册失败"+e.getMessage()));
        }
    }

    // 添加通过邮箱查找用户的接口
    @GetMapping("/email/{email}")
    public ResponseEntity<ApiResponse<User>> getUserByEmail(@PathVariable String email) {
        return userService.findByEmail(email)
                .map(user -> ResponseEntity.ok(ApiResponse.success(user)))
                .orElse(ResponseEntity.status(404).body(ApiResponse.error(404, "用户不存在")));
    }

    // 添加符合新路径规范的登录接口
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<LoginResponse>> loginUserNew(@RequestBody LoginRequest loginRequest){
        return userService.login(loginRequest.getUsername(), loginRequest.getPassword())
                .map(user -> {
                    // 生成访问令牌和刷新令牌
                    LoginResponse response = new LoginResponse();
                    response.setAccessToken(userService.generateToken(user));
                    response.setRefreshToken(userService.generateToken(user)); // 简化实现，实际应该生成不同的刷新令牌
                    response.setExpiresIn(3600L); // 1小时过期
                    
                    return ResponseEntity.ok(ApiResponse.success("登录成功", response));
                })
                .orElse(ResponseEntity.status(401).body(ApiResponse.error(401, "用户名或密码错误")));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<User>> getUserById(@PathVariable Long id){
        return userService.findById(id)
                .map(user -> ResponseEntity.ok(ApiResponse.success(user)))
                .orElse(ResponseEntity.status(404).body(ApiResponse.error(404, "用户不存在")));
    }
    
    // 用于注册响应的数据类
    public static class UserData {
        private Long userId;
        private String username;
        
        public Long getUserId() {
            return userId;
        }
        
        public void setUserId(Long userId) {
            this.userId = userId;
        }
        
        public String getUsername() {
            return username;
        }
        
        public void setUsername(String username) {
            this.username = username;
        }
    }
}